package unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author Panbo Guo
 * @date 2021/7/14
 */
public class CasLongTest {

    private long i = 0;

    private static Unsafe unsafe;
    private static long offset;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
            offset = unsafe.objectFieldOffset(CasLongTest.class.getDeclaredField("i"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CasLongTest test = new CasLongTest();
        unsafe.compareAndSwapLong(test, offset, 0, 1);

        System.out.println(test.i);
    }
}
